package com.yami.shop.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.InvoiceApprovalParam;
import com.yami.shop.bean.param.InvoiceParam;
import com.yami.shop.bean.param.UserCashOutApprovalParam;
import com.yami.shop.bean.vo.ComplaintSuggestionsVo;
import com.yami.shop.bean.vo.InvoiceVo;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.payment.WeChatPayment;
import com.yami.shop.payment.dto.GetJsapiServiceDto;
import com.yami.shop.payment.dto.TransferAccountsDto;
import com.yami.shop.security.admin.util.SecurityUtils;
import com.yami.shop.service.InvoiceService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserService;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 发票申请表 前端控制器
 * </p>
 *
 * @author jcd
 * @since 2024-08-19
 */
@RestController
@RequestMapping("/shop/invoice")
public class InvoiceController {
    @Autowired
    private UserService userService;
    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private OrderService orderService;

    /**
     * 分页查询
     *
     */
    @PreAuthorize("@pms.hasPermission('shop:invoice:page')")
    @GetMapping("/page")
    public ServerResponseEntity<IPage<ComplaintSuggestions>> page(PageParam page, InvoiceParam invoice) {
        LambdaQueryWrapper<Invoice> userFundDetailLambdaQueryWrapper = new LambdaQueryWrapper<>(invoice);

        userFundDetailLambdaQueryWrapper.exists(StringUtils.isNotBlank(invoice.getUserName()),"(select null from tz_user u where u.user_id = e_invoice.uid and u.nick_name like '%"+invoice.getUserName()+"%')");

        userFundDetailLambdaQueryWrapper.like(StringUtils.isNotBlank(invoice.getOrderNumberLike()),Invoice::getOrderNumber,invoice.getOrderNumberLike());

        userFundDetailLambdaQueryWrapper.orderByDesc(Invoice::getCreateTime);
        PageParam page1 = invoiceService.page(page,userFundDetailLambdaQueryWrapper);

        List<Invoice> records = page1.getRecords();

        List<InvoiceVo> list1=new ArrayList<>();
        for (Invoice detail:records){
            InvoiceVo vo=new InvoiceVo();
            BeanUtil.copyProperties(detail,vo);

            User byId = userService.getById(detail.getUid());
            if (byId != null){
                vo.setUserName(byId.getNickName());
            }
            list1.add(vo);
        }

        page1.setRecords(list1);
        return ServerResponseEntity.success(page1);
    }


    /**
     * 通过id查询开票申请
     *
     * @param id id
     * @return 单个数据
     */
    @PreAuthorize("@pms.hasPermission('shop:invoice:info')")
    @GetMapping("/info/{id}")
    public ServerResponseEntity<Invoice> getById(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(invoiceService.getById(id));
    }

    /**
     * 新增用户地址管理
     *
     * @return 是否新增成功
     */
    @SysLog("新增开票申请")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('shop:invoice:save')")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid Invoice invoice) {
        Long userId = SecurityUtils.getSysUser().getUserId();
        Invoice one = invoiceService.lambdaQuery().eq(Invoice::getOrderId, invoice.getOrderId()).one();
        if(one != null){
            return ServerResponseEntity.showFailMsg("订单的发票申请已存在");
        }

        invoice.setCreateTime(new Date());
        invoice.setCreateBy(userId);
        invoice.setDelFlag(0);

        Order byId = orderService.getById(invoice.getOrderId());
        if (byId != null){
            invoice.setOrderNumber(byId.getOrderNumber());
            invoice.setProdName(byId.getProdName());
            invoice.setProductNums(byId.getProductNums());
            invoice.setUid(byId.getUserId());
        }

        return ServerResponseEntity.success(invoiceService.save(invoice));
    }

    /**
     * 修改用户地址管理
     *
     * @return 是否修改成功
     */
    @SysLog("修改开票申请")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('shop:invoice:update')")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Invoice invoice) {
        Long userId = SecurityUtils.getSysUser().getUserId();

        invoice.setUpdateBy(userId);
        invoice.setUpdateTime(new Date());

        return ServerResponseEntity.success(invoiceService.updateById(invoice));
    }

    /**
     * 通过id删除用户地址管理
     *
     * @param id id
     * @return 是否删除成功
     */
    @SysLog("删除开票申请")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('shop:invoice:delete')")
    public ServerResponseEntity<Boolean> removeById(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(invoiceService.removeById(id));
    }

    @SysLog("发票审批")
    @PostMapping("/approval")
    @PreAuthorize("@pms.hasPermission('shop:invoice:update')")
    @Transactional
    public ServerResponseEntity<Boolean> approval(@RequestBody @Valid InvoiceApprovalParam param) {
        Long userId = SecurityUtils.getSysUser().getUserId();

        Invoice byId = invoiceService.getById(param.getId());
        if (byId == null) {
            return ServerResponseEntity.showFailMsg("查询提现记录不存在");
        }

        if (byId.getState() != 0) {
            return ServerResponseEntity.showFailMsg("当前提现记录 不能重复审核");
        }

        if (StringUtils.equals(param.getResult(), "0")) {
            //通过
            if (StringUtils.isBlank(param.getInvoiceImgUrl())) {
                return ServerResponseEntity.showFailMsg("通过必须上传发票");
            }
            Invoice invoice=new Invoice();
            invoice.setId(byId.getId());
            invoice.setState(1);//已开票
            invoice.setInvoiceImgUrl(param.getInvoiceImgUrl());
            invoiceService.updateById(invoice);
        } else if (StringUtils.equals(param.getResult(), "1")) {
            //驳回
            if (StringUtils.isBlank(param.getRejectReason())) {
                return ServerResponseEntity.showFailMsg("驳回必须填写原因");
            }
            Invoice invoice=new Invoice();
            invoice.setId(byId.getId());
            invoice.setState(2);//驳回
            invoice.setRejectReason(param.getRejectReason());
            invoiceService.updateById(invoice);
        }

        return ServerResponseEntity.success(true);
    }
}

